package com.nightcat.dogvscat;

import java.util.Random;

import android.app.Activity;
import android.graphics.RectF;
import android.graphics.drawable.AnimationDrawable;
import android.os.Bundle;
import android.os.Handler;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.ImageView;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.nightcat.dogvscat.GameView.Callback;

public class DogvsCatActivity extends Activity {
	protected static final String TAG = "DogvsCatActivity";
	private static final float PROGRESS_BAR_LENGTH = 100;
	private GameView mGameCanvas;
	private ImageView mLeftPlayer;
	private ImageView mRightPlayer;
	
	private boolean needSavePower;
	private boolean needSavePowerDog;
	
	/**
	 * 蓄力条，当按住游戏角色的时候，蓄力条出现并开始蓄力，
	 * 放开角色时出发投掷动作。
	 */
	private ProgressBar mProgress;
	private float mProgressStatus = 0;
	
	private ProgressBar mProgressDog;
	private float mProgressStatusDog = 0;
	
	private static final int RUN_PERIOD = 20;
	private Handler mHandler = new Handler();
	
	//左右血条。
	private ProgressBar mLeftLife;
	private ProgressBar mRightLife;
	
	//血条的值。
	private int mLeftLifeValue;
	private int mRightLifeValue;
	
	//随机数生成器。
	private Random mRandom = new Random();
	private static final int LEFT_PLAYER = 0;
	private static final int RIGHT_PLAYER = 1; 
	
	//风向和风力标。
	private int mWindDirection;
	private double mWindStrength;
	private ImageView windIndicator;
	private TextView mLeftWindIndicator;
	private TextView mRightWindIndicator;
	
	//判断胜负。
	public static final int LEFT_WIN = 0;
	public static final int RIGHT_WIN = 1;
	public static final int NO_WIN = -1;
	
	//当前可以发起攻击的角色。
	private int mCurrentPlayer = RIGHT_PLAYER;
	
	//道具栏。
	private ImageView mLeftSelected_icon;
	private ImageView mRightSelected_icon;
	
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        windIndicator = (ImageView) findViewById(R.id.wind_direction);
        mGameCanvas = (GameView) this.findViewById(R.id.gameview);
        mLeftPlayer = (ImageView) this.findViewById(R.id.cat);
        mRightPlayer = (ImageView) this.findViewById(R.id.dog);
        mLeftSelected_icon = (ImageView) this.findViewById(R.id.left_selected);
        mRightSelected_icon = (ImageView) this.findViewById(R.id.right_selected);
        
        mProgress = (ProgressBar) findViewById(R.id.savePower);
        mProgressDog = (ProgressBar) findViewById(R.id.savePowerDog);
        
        //为左右血条初始化值。
        mLeftLife = (ProgressBar) findViewById(R.id.leftLifeValue);
        mLeftLifeValue = mLeftLife.getMax();
        mLeftLife.setProgress(mLeftLifeValue);
        mRightLife = (ProgressBar) findViewById(R.id.rightLifeValue);
        mRightLifeValue = mRightLife.getMax();
        mRightLife.setProgress(mRightLifeValue);
        
        //初始化风力指示剂。
        mLeftWindIndicator = (TextView) this.findViewById(R.id.left_wind_strength);
        mRightWindIndicator = (TextView) this.findViewById(R.id.right_wind_strength);
        
        /**
         * 根据当前风向设置风向标。
         * 根据当前风力设置风力标。
         */
        setWindDrection();
        
        /**
         * 加载音乐。
         */
        final int mSound_save_power = Util.loadMusic(R.raw.save_power,this);
        final int mSound_flying = Util.loadMusic(R.raw.flying,this);
        
        mLeftPlayer.setOnTouchListener(new OnTouchListener(){
        	final AnimationDrawable frameAnimation = (AnimationDrawable) mLeftPlayer.getBackground();
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch(event.getAction()){
					case MotionEvent.ACTION_DOWN:
						needSavePower = true;
						mProgress.setVisibility(View.VISIBLE);
						mLeftSelected_icon.setVisibility(View.INVISIBLE);
						mHandler.post(run_savePower);
						frameAnimation.stop();
						//开始播放蓄力条的声音。
						Util.playMusic(mSound_save_power,DogvsCatActivity.this);
						break;
					case MotionEvent.ACTION_UP:
						disableTouch();
						needSavePower = false;
						mProgress.setVisibility(View.INVISIBLE);
						
						mHandler.postDelayed(new Thread(){
							public void run(){
						    	/**
						    	 * 計算播放動畫需要的時間。
						    	 */
						    	int totalDuration = 0;
						    	for (int i = 0; i < frameAnimation.getNumberOfFrames(); i++) {
						    		totalDuration += frameAnimation.getDuration(i);
						        }
						    	
						    	frameAnimation.start();
						    	/**
						    	 * 動畫結束后再觸發此動作。
						    	 */
						    	mHandler.postDelayed(new Runnable(){
						    		public void run(){
//						    			Log.d(TAG,"mProgressStatus"+String.valueOf(mProgressStatus));
//						    			Log.d(TAG,"mProgressStatus/PROGRESS_BAR_LENGTH:"+String.valueOf(mProgressStatus/PROGRESS_BAR_LENGTH));
						    			mGameCanvas.startCatAction((float) (mProgressStatus/PROGRESS_BAR_LENGTH*getWindFactor(LEFT_PLAYER)));
						    			mProgressStatus = 0;
						    		}
						    	}, totalDuration);
							}
						},RUN_PERIOD);
						
						Util.playMusic(mSound_flying,DogvsCatActivity.this);
						break;
				}
				return true;
			}
        	
        });
        
        mRightPlayer.setOnTouchListener(new OnTouchListener(){
        	final AnimationDrawable frameAnimation = (AnimationDrawable) mRightPlayer.getBackground();
			@Override
			public boolean onTouch(View v, MotionEvent event) {
				switch(event.getAction()){
					case MotionEvent.ACTION_DOWN:
						needSavePowerDog = true;
						mProgressDog.setVisibility(View.VISIBLE);
						mRightSelected_icon.setVisibility(View.INVISIBLE);
						mHandler.post(run_savePower_dog);
						frameAnimation.stop();
						//开始播放蓄力条的声音。
						Util.playMusic(mSound_save_power,DogvsCatActivity.this);
						break;
					case MotionEvent.ACTION_UP:
						disableTouch();
						needSavePowerDog = false;
						mProgressDog.setVisibility(View.INVISIBLE);
						
						mHandler.postDelayed(new Thread(){
							public void run(){
						    	/**
						    	 * 計算播放動畫需要的時間。
						    	 */
						    	int totalDuration = 0;
						    	for (int i = 0; i < frameAnimation.getNumberOfFrames(); i++) {
						    		totalDuration += frameAnimation.getDuration(i);
						        }
						    	
						    	frameAnimation.start();
						    	/**
						    	 * 動畫結束后再觸發此動作。
						    	 */
						    	mHandler.postDelayed(new Runnable(){
						    		public void run(){
//						    			Log.d(TAG,"mProgressStatus"+String.valueOf(mProgressStatus));
//						    			Log.d(TAG,"mProgressStatus/PROGRESS_BAR_LENGTH:"+String.valueOf(mProgressStatus/PROGRESS_BAR_LENGTH));
						    			mGameCanvas.startDogAction((float) (mProgressStatusDog/PROGRESS_BAR_LENGTH*getWindFactor(RIGHT_PLAYER)));
						    			mProgressStatusDog = 0;
						    		}
						    	}, totalDuration);
							}
						},RUN_PERIOD);
						
						Util.playMusic(mSound_flying,DogvsCatActivity.this);
						break;
				}
				return true;
			}
        	
        });
    }  
    
    
    private Runnable run_savePower = new Runnable() {
            public void run() {
                if (needSavePower && mProgressStatus<PROGRESS_BAR_LENGTH) {
                    mProgressStatus++;
                    mProgress.setProgress((int)mProgressStatus);
                    mHandler.postDelayed(this,RUN_PERIOD);
                }
            }
    };
    
    private Runnable run_savePower_dog = new Runnable() {
        public void run() {
            if (needSavePowerDog && mProgressStatusDog<PROGRESS_BAR_LENGTH) {
                mProgressStatusDog++;
                mProgressDog.setProgress((int)mProgressStatusDog);
                mHandler.postDelayed(this,RUN_PERIOD);
            }
        }
    };
    
    /**
     * 更新血条。
     * @param lostPercent 按百分比更新血条，此参数大于0小于1.
     */
    public void setLeftLifeValue(float lostPercent){
    	mLeftLifeValue = (int) (((float)mLeftLifeValue)- mLeftLife.getMax()*lostPercent);
    	mLeftLife.setProgress(mLeftLifeValue);
    }
    
    public void setRightLifeValue(float lostPercent){
    	mRightLifeValue = (int) (((float)mRightLifeValue)*mRightLife.getMax()*lostPercent);
    	mRightLife.setProgress(mRightLifeValue);
    }

	@Override
    public void onResume(){
    	super.onResume();
    }
	
	/**
	 * player的位置信息必须在player显示出来以后才能得到，所以放在此方法中。
	 * 存在方法被执行多次的情况。
	 * TODO 找到更合适的函数去执行以下工作。
	 */
	@Override
	public void onWindowFocusChanged(boolean hasFocus) {
		super.onWindowFocusChanged(hasFocus);
		Log.d(TAG, "onWindowFocusChanged");
		
		if(mGameCanvas.getCallback() == null){
			//gameView的回调函数。
		   	Callback callback = new GameView.Callback(){
		   		@Override
		   		public int changeWindDirection() {
		   			return setWindDrection();
		   		}
	
				@Override
				public RectF getLeftPlayerRect() {
					return new RectF(mLeftPlayer.getLeft(),mLeftPlayer.getTop(),mLeftPlayer.getLeft()+mLeftPlayer.getWidth(),mLeftPlayer.getTop()+mLeftPlayer.getHeight());
				}
	
				@Override
				public RectF getRightPlayerRect() {
					return new RectF(mRightPlayer.getLeft(),mRightPlayer.getTop(),mRightPlayer.getLeft()+mRightPlayer.getWidth(),mRightPlayer.getTop()+mRightPlayer.getHeight());
				}

				//同一时刻只有一方相应点击事件。
				@Override
				public void exchangePlayer() {
					if(mCurrentPlayer == RIGHT_PLAYER){
						mCurrentPlayer = LEFT_PLAYER;
						mRightPlayer.setEnabled(false);
						mLeftPlayer.setEnabled(true);
						mLeftSelected_icon.setVisibility(View.VISIBLE);
					}else{
						mCurrentPlayer = RIGHT_PLAYER;
						mLeftPlayer.setEnabled(false);
						mRightPlayer.setEnabled(true);
						mRightSelected_icon.setVisibility(View.VISIBLE);
					}
				}

		   	};
	        mGameCanvas.registerCallback(callback);
	        mGameCanvas.init();
		}
	}
	

	@Override
	public void openContextMenu(View view) {
		// TODO Auto-generated method stub
		super.openContextMenu(view);
	}

	@Override
	protected void onPause() {
		super.onPause();
	}

	@Override
    public void onDestroy(){
    	super.onDestroy();
    	mGameCanvas.stopAction();
    }
    
    /**
     * 获得随机的方向，0代表风向向左，1代表风向向右。
     * @return
     */
    private int getRadomWindDirection(){
    	return mRandom.nextInt()%2;
    }
    
    /**
     * 获得随机风力，风力用百分比来表示，(0,1)
     * @return
     */
    private double getRadomWindStrength(){
    	return mRandom.nextFloat()%0.5;
    }
     
    /**
     * 综合风力和风向，获得综合影响指数。
     * playerPosition 0代表左边player，1代表右边player
     * @return
     */
    private double getWindFactor(int playerPosition){
    	//风向向左
    	if(mWindDirection==0){
    		if(playerPosition == LEFT_PLAYER){
    			return 1-mWindStrength;
    		}else{
    			return 1+mWindStrength;
    		}
    	}else{
    		if(playerPosition == LEFT_PLAYER){
    			return 1+mWindStrength;
    		}else{
    			return 1-mWindStrength;
    		}
    	}
    }
    
    /**
     * 设置方向标的方向。
     * 设置风力指示剂的值。
     * @return
     */
    private int setWindDrection(){
    	 //获得当前风力设置风力值。
	     mWindStrength = getRadomWindStrength();
	     
    	 mWindDirection = getRadomWindDirection();
         if(mWindDirection == 0){
         	windIndicator.setImageResource(R.drawable.wind_direction_left);
         	mLeftWindIndicator.setText(getCurrentStrengthIndicator());
         	mLeftWindIndicator.setVisibility(View.VISIBLE);
         	mRightWindIndicator.setVisibility(View.INVISIBLE);
         }else{
         	windIndicator.setImageResource(R.drawable.wind_direction_right);
         	mRightWindIndicator.setText(getCurrentStrengthIndicator());
         	mRightWindIndicator.setVisibility(View.VISIBLE);
         	mLeftWindIndicator.setVisibility(View.INVISIBLE);
         }
         return mWindDirection;
    }
    
    //将当前风力的大小图形化。
    private String getCurrentStrengthIndicator(){
    	StringBuilder result = new StringBuilder();
    	double i = 0.0d;
    	Log.d(TAG, "WIND_STRENGTH:"+mWindStrength);
    	while(i < mWindStrength){
    		if(i == 0.0d){
    			i+=0.1d;
    			continue;
    		}
    		if(mWindDirection == 0){
    			result.append("<");
        	}else{
        		result.append(">");
        	}
    		i+=0.1d;
    	}
    	return result.toString();
    }
    
    //播放背景音乐。
    private void playBackground(){
    	
    }
    
    /**
     * 检测赢家
     * @return 0 左边嬴，1 右边嬴, -1 都没赢
     */
    public int checkWhoWin(){
    	if(mLeftLifeValue == 0){
    		return RIGHT_WIN;
    	} else if(mRightLifeValue == 0){
    		return LEFT_WIN;
    	} 
    	return NO_WIN;
    }
    
	/**
	 * 禁用player的对touch的响应。
	 */
	public void disableTouch() {
		mRightPlayer.setEnabled(false);
		mLeftPlayer.setEnabled(false);
	}
    
}